package com.zhen.servlet;

import com.zhen.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LonginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置页面编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //表单获取账号密码
        String username = req.getParameter("u");
        String password = req.getParameter("p");
        System.out.println("------登入-------");
        System.out.println("username="+username);
        System.out.println("password="+password);
        //seesion获取验证码的值
        HttpSession session = req.getSession();
        Object code = session.getAttribute("code");
        System.out.println("code="+code);
        //表单获取用户输入的验证码
        String code1 = req.getParameter("c");
        PrintWriter writer = resp.getWriter();
        if (code != null && code.equals(code1)) {
            String sql = "SELECT `id` ,`name` FROM `user` WHERE username=? AND `password`=md5(?)";
            Long aLong = JdbcUtils.select(sql, Long.class, username, password);
            if (aLong != null && aLong > 0) {
                session.setAttribute("UID", aLong);
                String sql2="SELECT `name` FROM `user` WHERE `id`=?";
                String UNAME = JdbcUtils.select(sql2, String.class, aLong);
                session.setAttribute("UNAME",UNAME);
                System.out.println("设置uid,uid="+aLong);
                resp.sendRedirect("/zhen/index.jsp");
                System.out.println("-------登录成功------");
            }else {
                System.out.println("账号或密码错误");
                System.out.println("-------登录失败------");
//                session.setAttribute("loginError","账号或密码错误");
                resp.sendRedirect("/zhen/login.jsp");
            }
        } else {
            System.out.println("验证码错误");
            System.out.println("-------登录失败------");
//            session.setAttribute("loginError","验证码错误");
            resp.sendRedirect("/zhen/login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
